<template>
<div class="buyertotcf">

  <div>
    <el-breadcrumb @click="specialInitialProcess" separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/initiatingprocess' }" v-if="isShowItem">{{process[processNumber]}}</el-breadcrumb-item>
      <span @click.stop=";" v-if="isShowSpan">{{process[processNumber]}}<i class="el-icon-arrow-right"></i> </span>
      <span @click.stop=";">买家付定金给TCF</span>
    </el-breadcrumb>
  </div>

  <div class="buyertotcf-top">
    <h2>定金收汇通知单</h2>

    <div class="head">
      <div class="btns clearfix">
        <el-button v-show="!hasBind" class="bind" :disabled="!editable" type="primary" @click="bindOrder">绑定订单</el-button>
        <!-- <el-button v-if="hasBind"  class="export" :disabled="!editable" type="primary">导出</el-button> -->
        <!-- <el-button v-else class="export" :disabled="true" type="primary">导出</el-button> -->
      </div>

      <div class="select-orders">
        <el-row :gutter="20">
          <el-col :span="10">
            <div>
              <p class="select-orders-line">
                选中的外贸订单
                <el-button v-show="hasBind"  @click="bindOrder" type="text">点击修改</el-button>
              </p>
              <ul>

                <!-- <li v-if="isFromServer"><a href="#">{{saveData.buyertotcf_bindFContracts[0]}}</a></li> -->
                <!-- <li v-else-if="showftc"><a :href="'#/initiatingprocess/businessform?dTab=3&formInstId='+ showftc.id + '&formServiceName=' +  showftc.formServiceName">{{saveData.buyertotcf_bindFContracts[0]}}</a></li> -->

                <li><a href="#">{{saveData.buyertotcf_bindFContracts[0]}}</a></li>
              </ul>
            </div>
          </el-col>
          <el-col :span="10" :offset="4">
            <div>
              <p class="select-orders-line">选中的内贸订单</p>
              <!-- <ul v-if="!isFromServer">
                <li v-for="(item,index) in showdtcs">
                  <a :href="'#/initiatingprocess/businessform?dTab=' + item.dtcId + '&formInstId=' + item.formInstId + '&formServiceName=' +  showftc.formServiceName">{{item.bd_no}}</a>
                </li>
              </ul>

              <ul v-else>
                <li v-for="(item,index) in saveData.buyertotcf_bindDContracts">
                  <a href="#">{{item}}</a>
                </li>
              </ul> -->

              <ul>
                <!-- <li v-for="(item,index) in saveData.buyertotcf_bindDContracts">
                  <a href="#">{{item}}</a>
                </li> -->

                <li>
                  <a href="#">{{saveData.buyertotcf_bindDContracts[0]}}</a>
                </li>
              </ul>

            </div>
          </el-col>
        </el-row>
      </div>



      <div class="bind-window">
        <el-dialog title="订单绑定" width="70%" :visible.sync="dialogCtrl.outerVisible">

          <el-form :inline="true">
            <el-form-item label="订单编号">
              <el-input v-model="orderNumber" placeholder="请输入订单编号"></el-input>
            </el-form-item>
            <el-form-item label="外贸合同号">
              <el-input v-model="foreignTradeContractNumber" placeholder="请输入外贸合同号"></el-input>
            </el-form-item>

            <el-form-item label="买家名称">
              <el-input v-model="buyerName" placeholder="请输入买家名称"></el-input>
            </el-form-item>

            <el-form-item>
              <el-date-picker
              v-model="orangeDate"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOrange">
            </el-date-picker>
          </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="queryFtc(-1)">查询</el-button>
            </el-form-item>
          </el-form>

          <el-table v-loading="loading" :data="table1Data" style="width: 100%" border>
            <el-table-column prop="table1_orderNumber" label="订单编号" sortable width="240" :sort-method="table1Sort">
              <template slot-scope="scope">
                  <span>
                    <input type="checkbox" :value="scope.row.table1_id" @click="checkBoxRadio('f', $event)" v-model="buyertotcf_selectOrder">
                    <span>{{scope.row.table1_orderNumber}}</span>
                  </span>
                </template>
            </el-table-column>

            <el-table-column prop="table1_ftcNumber" label="外贸合同号" sortable>
            </el-table-column>

            <el-table-column prop="table1_createTime" label="订单生成时间" sortable>
            </el-table-column>

            <el-table-column prop="table1_buyerName" label="买家名称" >
            </el-table-column>

            <el-table-column prop="table1_orderProcess" label="订单流程" >
            </el-table-column>

            <el-table-column prop="table1_orderStatus" label="订单状态" >
            </el-table-column>
          </el-table>

          <div class="pageing">
            <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page.currPage"
            :page-sizes="[20, 30, 50, 100]"
            :page-size="page.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.totalSize">
          </el-pagination>

          </div>



          <el-dialog width="50%" title="内贸合同绑定" :visible.sync="dialogCtrl.innerVisible" append-to-body>

            <el-table v-loading="loading" :data="table2Data" style="width: 100%" border>
              <el-table-column prop="table2_dtcNumber" label="内贸合同编号" width="200">
                <template slot-scope="scope">
                    <span>
                      <input type="checkbox" @click="checkBoxRadio('d', $event)" :value="scope.row.table2_id" v-model="buyertotcf_selectOrder2">
                      <span>{{scope.row.table2_dtcNumber}}</span>
                    </span>
                  </template>
              </el-table-column>

              <el-table-column prop="table2_sellerName" label="供方名称">
              </el-table-column>

              <el-table-column prop="table2_contractAmount" label="合同金额">
              </el-table-column>
            </el-table>

            <div slot="footer" class="dialog-footer">
              <el-button type="primary" :disabled="canNotSelect2" @click="bindInnerConfirm">确定</el-button>
              <el-button @click="bindInnerCancel">取 消</el-button>
            </div>
          </el-dialog>

          <div slot="footer" class="dialog-footer">
            <el-button type="primary" :disabled="canNotSelect" @click="bindOuterSelect">选择内贸合同</el-button>
            <el-button @click="bindOuterCancel">取 消</el-button>
          </div>

        </el-dialog>
      </div>
    </div>

    <div class="upload">
      <p class="upload-hint">票据/附件</p>
      <div>
        <div class="upload-btn">
          <input type="file"  v-show="hasBind ? editable : false"  name="file" multiple @change="selectFiles">
          <el-button v-if="hasBind"  type="primary" :disabled="!editable">选择附件</el-button>
          <el-button v-else type="primary" :disabled="true">选择附件</el-button>
        </div>

        <ul class="upload-files">
          <li @mouseover="handleOver(item)" :key="index"   @mouseout="handleOut(item)" v-for="(item,index) in saveData.attachedFiles">
            <span @click="download(item.id, $event)">{{item.name}}</span>
            <span v-if="editable && item.status" class="el-icon-circle-check" style="color:#67c23a;"></span>
            <span v-else-if="editable" class="el-icon-circle-close" @click="changeFiles(index,item)" style="color:red;"></span>
          </li>
        </ul>
      </div>
    </div>
  </div>

  <div class="buyertotcf-bottom">
    <fixed-form v-if="hasBind" :editable="editable" :saveAndSend="saveAndSend" ref="fixedForm" :datas="allData" :sendMenus="sendMenus" processName="buyertotcf" />
    <fixed-form v-else :editable="false" :saveAndSend="false" ref="fixedForm" :datas="allData" :sendMenus="sendMenus" processName="buyertotcf" />
  </div>

</div>
</template>

<script>
import fixedForm from '../common/fixedForm';

import {
  uploadFiles,
  getSendMenus,
  getData,
  queryBindContracts,
  queryBindDtcContracts
} from '@/server/initiatingprocess';
import {
  getStore,
  setStore
} from '@/assets/js/common'

import {filedownload , deleteFile} from '@/server/customermanagement/index.js'

export default {
  created() {
    this.allData = _.cloneDeep(this.saveData);
    setStore("flow2-save-status", "unsave");
  },

  beforeRouteEnter(to, from, next) {

    let dom = document.querySelector('.initiatingprocess  .routers-ctrl');
    if (dom) {
      dom.style.zIndex = '-1';
    }

    next((vm) => {
      //说明从其他位置跳到该流程中
      if (to.query.dTab) {

        vm.processNumber = parseInt(to.query.itemStatus);

        if (to.query.isHive == 1) {
          getData({
            formInstId: to.query.formInstId,
            formServiceName: to.query.formServiceName,
            isHive: 1
          }).then((response) => {
            let data = response.data.datas[0];

            //对其中的字符串类型的附件名称，进行分割
            data = JSON.parse(JSON.stringify(data).replace(/(attachedFiles)/g, function(){return 'useless01';}).replace(/(attachedFileList)/g, function() {
              return "attachedFiles";
            }).replace(/(relationFormInst)/g, function(){ return 'relationFormInstId'}), function(k, v) {
              if (k === 'attachedFiles') {

                if (Array.isArray(v)) {
                  return v.map((e) => {
                    return {
                      name: e.realFileName,
                      status: 1,
                      id: e.id
                    };
                  });
                } else {
                  return [];
                }
              }


              if (k === 'relationFormInstId'){
                if (_.isPlainObject(v)){
                  return [v];
                } else {
                  return [];
                }
              }

              if ((k.indexOf("_bindFContracts") != -1) || (k.indexOf("_bindDContracts") != -1)) {
                if (_.isString(v)){
                  return v.split(',');
                } else {
                  return [];
                }
              }

              return v;
            });

            for (const key in data) {
              vm.$set(vm.saveData, key, data[key]);
            }
            
            vm.hasBind = true;

            let approvalIndex, approvalFullName, names = [], originApprovals = _.cloneDeep(vm.saveData.originApprovals);

            if (data.role) {
              vm.editable = data.role.DEFAULT == 'W' ? true : false;
              vm.saveAndSend = vm.editable;


              let copyApprovals = _.cloneDeep(data.approvals);


              for (let i = 0; i < copyApprovals.length ; i++) {
                for (var prop in originApprovals[i]) {
                  if ((prop != 'rw') && (prop != 'approval_div_name') && (prop != 'item')){
                    originApprovals[i][prop] = copyApprovals[i][prop]
                  }
                }
              }

              
              vm.$set(vm.saveData, "originApprovals", originApprovals);
              vm.$set(vm.saveData, "isSalesMan", false );
            } else {
              vm.$set(vm.saveData, "isSalesMan", true);
            }


            getSendMenus({
              flowId: to.query.flowId,
              currNodeId: to.query.currNodeId
            }).then((response) => {
              vm.sendMenus = response.data.datas[0];
              vm.allData = _.cloneDeep(vm.saveData);
            });
          });
        } else {
          getData({
            formInstId: to.query.formInstId,
            formServiceName: to.query.formServiceName
          }).then((response) => {
            let data = response.data.datas[0];

            /*
            let data = {
                "buyertotcf_bindFContracts": "ZS20171203wwwww",
                "buyertotcf_bindDContracts": "ZS20171203F",
                "id": 10,
                "attachedFileList": [
                    {
                        "id": 25,
                        "createTime": 1529893107000,
                        "modifyTime": 1529893110000,
                        "fileName": "attached/1529893107874_989898.png",
                        "type": 2,
                        "status": 1,
                        "formInstId": 90,
                        "tabName": "buyertotcf",
                        "tabId": 10,
                        "customerId": null,
                        "realFileName": "989898.png"
                    }
                ],
                "formInstId": 90,
                "flowId": 2,
                "formId": 2,
                "formServiceName": "buyertotcf",
                "bindingFormInstId": 23,
                "orderCode": "NO.DD2018051800112",
                "approvals": [],
                "role": [
                    {
                        "id": 46,
                        "createTime": 1525752207000,
                        "modifyTime": null,
                        "formId": 2,
                        "flowId": 2,
                        "flowNodeId": 7,
                        "flowNodeName": "业务填报",
                        "itemName": "buyertotcf_bindFContracts",
                        "permission": "W"
                    },
                    {
                        "id": 47,
                        "createTime": 1525752207000,
                        "modifyTime": null,
                        "formId": 2,
                        "flowId": 2,
                        "flowNodeId": 7,
                        "flowNodeName": "业务填报",
                        "itemName": "buyertotcf_bindDContracts",
                        "permission": "W"
                    },
                    {
                        "id": 48,
                        "createTime": 1525752207000,
                        "modifyTime": null,
                        "formId": 2,
                        "flowId": 2,
                        "flowNodeId": 7,
                        "flowNodeName": "业务填报",
                        "itemName": "item_02_01",
                        "permission": "R"
                    },
                    {
                        "id": 49,
                        "createTime": 1525752207000,
                        "modifyTime": null,
                        "formId": 2,
                        "flowId": 2,
                        "flowNodeId": 7,
                        "flowNodeName": "业务填报",
                        "itemName": "item_02_02",
                        "permission": "R"
                    }
                ]
            };
            */


            //对其中的字符串类型的附件名称，进行分割
            data = JSON.parse(JSON.stringify(data).replace(/(attachedFiles)/g, function(){return 'useless01';}).replace(/(attachedFileList)/g, function() {
              return "attachedFiles";
            }).replace(/(relationFormInst)/g, function(){ return 'relationFormInstId'}), function(k, v) {
              if (k === 'attachedFiles') {
                if (_.isArray(v)) {
                  return v.map((e) => {
                    return {
                      name: e.realFileName,
                      status: 1,
                      id: e.id
                    };
                  });
                } else {
                  return [];
                }
              }

              if (k === 'relationFormInstId'){
                if (_.isPlainObject(v)){
                  return [v];
                } else {
                  return [];
                }
              }

              if ((k.indexOf("_bindFContracts") != -1) || (k.indexOf("_bindDContracts") != -1)) {
                if (_.isString(v)){
                  return v.split(',');
                } else {
                  return [];
                }
              }

              return v;
            });



            for (const key in data) {
              vm.$set(vm.saveData, key, data[key]);
            }
            vm.hasBind = true;

            let approvalIndex, approvalFullName, names = [], 
            originApprovals = _.cloneDeep(vm.saveData.originApprovals);

            if (data.role) {
              data.role.forEach((e) => {
                if (e.itemName.indexOf("item") === -1) {
                  vm.$set(vm.roles, e.itemName, e.permission);
                } else {
                  let num = Number(e.itemName[e.itemName.length - 1]) - 1;
                  if (e.permission == 'W') {
                    approvalIndex = num;
                    approvalFullName = e.itemName;
                  }
                }
              });

              vm.editable = (vm.roles.buyertotcf_bindFContracts == 'W') ? true : false;
              vm.saveAndSend = true;


              let copyApprovals = _.cloneDeep(data.approvals);


              if (approvalIndex !== undefined) {
                if (approvalIndex >= 0) {
                  for (let i = 0; i <= approvalIndex; i++) {
                    if (copyApprovals[i]){
                      for (var prop in originApprovals[i]) {
                        if ((prop != 'rw') && (prop != 'approval_div_name') && (prop != 'item')){
                          originApprovals[i][prop] = copyApprovals[i][prop]
                        }
                      }
                      originApprovals[i].approval_id = '' + copyApprovals[i].id;
                    }
                  }
                }

                let date = new Date();
                originApprovals[approvalIndex].rw = 'W';
                originApprovals[approvalIndex].approval_time = date.toLocaleDateString() + ' ' + date.toTimeString().slice(0, 9);
                originApprovals[approvalIndex].approval_username = JSON.parse(getStore('userMsg')).userName;;

              } else if (copyApprovals.length > 0){
                for (let i = 0; i < copyApprovals.length; i++) {

                  for (var prop in originApprovals[i]) {
                    if ((prop != 'rw') && (prop != 'approval_div_name') && (prop != 'item')){
                      originApprovals[i][prop] = copyApprovals[i][prop]
                    }
                  }
                  originApprovals[i].approval_id = '' + copyApprovals[i].id;
                }
              }


              vm.$set(vm.saveData, "originApprovals", originApprovals)
              vm.$set(vm.saveData, "isSalesMan", false)
            } else {
              vm.$set(vm.saveData, "isSalesMan", true)
            }

            getSendMenus({
              flowId: to.query.flowId,
              currNodeId: to.query.currNodeId
            }).then((response) => {
              vm.sendMenus = response.data.datas[0];
              vm.allData = _.cloneDeep(vm.saveData);
            });
          });
        }
      } else {
        //  vm.$message({
        //    message: '请先绑定订单，否则无法保存和发送',
        //    type: 'warning',
        //    duration: 3000,
        //    showClose: true
        //  });
       }
    });
  },

  beforeRouteLeave(to, from, next){
    document.querySelector('.initiatingprocess  .routers-ctrl').style.zIndex = '-1';
    if (getStore("flow2-save-status") === 'unsave'){
      this.$confirm('您填写的内容尚未保存或发送,是否要离开?', '提示', {
        confirmButtonText: '离开',
        cancelButtonText: '留下',
        type: 'warning'
      }).then(() => {
        next();
      }).catch(() => {
        Array.prototype.forEach.call(document.getElementsByTagName('*'), (e) => {
          e.blur();
        });
        next(false);
      });
    } else {
      next();
    }
  },
  mounted() {
    //刷新浏览器时，避免重叠
    document.querySelector('.initiatingprocess  .routers-ctrl').style.zIndex = '-1';


    let that = this;
    let closeDom = document.querySelectorAll('.bind-window i.el-dialog__close.el-icon-close');
    for (let i = 0; i < closeDom.length; i++) {
      closeDom[i].onclick = function() {
        that.bindInnerCancel();
      };
    }

    getSendMenus({
      'flowId': 2
    }).then((response) => {
      this.sendMenus = response.data.datas[0];
    });

    //判断面包屑二级路由是否可退回
    let isCreatFlow = getStore('isCreatFlow');
    this.isShowItem = !isCreatFlow ? false : true;
    this.isShowSpan = !isCreatFlow ? true : false;
  },
  methods: {
    specialInitialProcess() {
      let cls = event.target.classList;
      if (cls.contains("el-icon-arrow-right") && cls.contains("el-breadcrumb__separator")) return;

      let dom = document.querySelector('.initiatingprocess .routers-ctrl');
      if (dom) {
        dom.style.zIndex = '0';
      }
    },

    selectFiles(event) {
      //票据附件
      let self = this;

      let attachedFiles = _.cloneDeep(self.saveData.attachedFiles);

      //直接上传，并且获得后端返回的文件的url,将url保存到 this.data.attachedFiles中
      uploadFiles(event.target.files).then((resArr) => {
        resArr.forEach(function(res, i) {
          attachedFiles.push({
            name: event.target.files[i].name,
            status: 1,
            id: res.data.datas[0].id
          });

          self.$set(self.saveData, "attachedFiles", attachedFiles);
          self.allData = _.cloneDeep(self.saveData);
        });
      });
    },
    changeFiles(index,item) {
      let attachedFiles = _.cloneDeep(self.saveData.attachedFiles);
      deleteFile({'id':item.id}).then((res) => {
        if(res.code != 1 ){
          this.$message.error('删除失败，请检查网络后重试');
        } else {
          attachedFiles.splice(index, 1);
          this.$set(this.saveData, "attachedFiles",attachedFiles);
          this.allData = _.cloneDeep(this.saveData);
        }
      });
    },
    handleOver(item){
      item.status = 0;
      this.$forceUpdate();
    },
    handleOut(item){
      item.status = 1;
      this.$forceUpdate();
    },
    download(id, event){
      window.open('http://47.104.93.41/api/common/download?id='+id);
    },

    handleSizeChange(size){
      this.$set(this.page, "pageSize", size);
      //需要重新查询
      this.queryFtc(1, this.page.pageSize);
    },
    handleCurrentChange(currPage){
      this.$set(this.page, "currPage", currPage);
      //需要重新查询
      this.queryFtc(this.page.currPage, this.page.pageSize);
    },


    bindOrder() {
      this.$set(this.dialogCtrl, "outerVisible", true);
      this.canNotSelect = true;
      this.canNotSelect2 = true;
      this.buyertotcf_bindFContracts = []
      this.buyertotcf_bindDContracts = []

      this.orderNumber = '';
      this.foreignTradeContractNumber = '';
      this.buyerName = '';
      this.queryFtc(1, 30);
    },
    queryFtc(currPage, pageSize) {

      let startTime, endTime;
      if (currPage ==  -1){
        currPage = 1;
        this.page.currPage = 1;
        pageSize = this.page.pageSize;
      }

      //通过查询来获得外贸合同订单，并修改table1的数据来进行显示
      this.buyertotcf_selectOrder = [];
      this.loading = true;

      if (this.orangeDate) {
        startTime = new Date('' + this.orangeDate[0]).getTime();
        endTime = new Date('' + this.orangeDate[1]).getTime();
        queryBindContracts({
          flowId: 1,
          orderCode: this.orderNumber,
          ftcCode: this.foreignTradeContractNumber,
          buyerName: this.buyerName,
          currPage: currPage - 1,
          pageSize: pageSize,
          gt_createTime: startTime,
          lt_createTime: endTime
        }).then((response) => {

          this.loading = false;

          this.table1Data = [];
          this.table2Data = [];

          this.$set(this.page, "totalSize",  response.data.totalSize);
          this.queryOrderData = response.data.datas;

          let table1Data = [];
          for (let i = 0; i < this.queryOrderData.length; i++) {

            if (!table1Data[i]) {
              table1Data[i] = {};
            }
            table1Data[i].table1_orderNumber = this.queryOrderData[i].orderCode;
            table1Data[i].table1_ftcNumber = this.queryOrderData[i].ftcCode;
            table1Data[i].table1_buyerName = this.queryOrderData[i].buyerName;
            table1Data[i].table1_id = this.queryOrderData[i].id;

            let date = new Date(this.queryOrderData[i].createTime);
            let m = date.getMonth() + 1;
            m = m < 10 ? '0' + m  : m;
            let d = date.getDate();
            d = d < 10 ? '0' + d  : d;

            table1Data[i].table1_createTime = date.getFullYear() + '-' + m + '-' + d;

            switch(this.queryOrderData[i].formInstStatus){
              case 0:
              case 1:
              table1Data[i].table1_orderStatus = '流转中';
              break;
              case 2:
              table1Data[i].table1_orderStatus = '完结';
              break;
            }

            table1Data[i].table1_orderProcess = this.queryOrderData[i].flowName;
          }

          this.table1Data = table1Data;
        });
      } else {
        queryBindContracts({
          flowId: 1,
          orderCode: this.orderNumber,
          ftcCode: this.foreignTradeContractNumber,
          buyerName: this.buyerName,
          currPage: currPage - 1,
          pageSize: pageSize
        }).then((response) => {

          this.loading = false;

          this.table1Data = [];
          this.table2Data = [];

          this.$set(this.page, "totalSize",  response.data.totalSize);
          this.queryOrderData = response.data.datas;

          let table1Data = [];
          for (let i = 0; i < this.queryOrderData.length; i++) {

            if (!table1Data[i]) {
              table1Data[i] = {};
            }
            table1Data[i].table1_orderNumber = this.queryOrderData[i].orderCode;
            table1Data[i].table1_ftcNumber = this.queryOrderData[i].ftcCode;
            table1Data[i].table1_buyerName = this.queryOrderData[i].buyerName;
            table1Data[i].table1_id = this.queryOrderData[i].id;

            let date = new Date(this.queryOrderData[i].createTime);
            let m = date.getMonth() + 1;
            m = m < 10 ? '0' + m  : m;
            let d = date.getDate();
            d = d < 10 ? '0' + d  : d;

            table1Data[i].table1_createTime = date.getFullYear() + '-' + m + '-' + d;

            switch(this.queryOrderData[i].formInstStatus){
              case 0:
              case 1:
              table1Data[i].table1_orderStatus = '流转中';
              break;
              case 2:
              table1Data[i].table1_orderStatus = '完结';
              break;
            }

            table1Data[i].table1_orderProcess = this.queryOrderData[i].flowName;
          }

          this.table1Data = table1Data;
        });
      }
    },
    table1Sort(a, b) {
      let a1 = a.toString().slice(a.length - 5);
      let b1 = b.toString().slice(b.length - 5);
      return parseInt(b) - parseInt(b);
    },

    checkBoxRadio(type, event) {

      if (type == 'f') {
        let value = event.target.value;

        if (value === this.buyertotcf_selectOrder[0]) {
          this.canNotSelect = true;
        } else {
          this.canNotSelect = false;
        }

        this.buyertotcf_selectOrder = [value];

        this.showftc = this.queryOrderData.find((e) => {
          // return e.orderCode == this.buyertotcf_selectOrder[0]
          return e.id == this.buyertotcf_selectOrder[0]
        });

        this.buyertotcf_bindFContracts.splice(0, 1, this.showftc.ftcCode)

      } else if (type == 'd') {
        let value = event.target.value;
        if (value === this.buyertotcf_selectOrder2[0]) {
          this.canNotSelect2 = true;
        } else {
          this.canNotSelect2 = false;
        }

        this.buyertotcf_selectOrder2 = [value];

        let currDtc = this.queryOrderData2.find(e => {
         return e.id == this.buyertotcf_selectOrder2[0]
        });
        this.buyertotcf_bindDContracts.splice(0, 1, currDtc.bd_no);
      }

    },


    bindOuterSelect() {
      let that = this;
      this.$set(this.dialogCtrl, "innerVisible", true)

      let closeDom = document.querySelectorAll('i.el-dialog__close.el-icon-close');
      for (let i = 0; i < closeDom.length; i++) {
        closeDom[i].onclick = function() {
          that.bindInnerCancel();
        };
      }


      this.buyertotcf_bindDContracts = [];
      /*
      需要根据当前选中的订单值即 checkedFOrder,来修改 table2Data，用于显示该订单下的内贸订单
      */

      // this.showftc = this.queryOrderData.find((e) => {
      //   return e.ftcCode == this.buyertotcf_bindFContracts[0]
      // });


      this.$set(this.saveData, "buyerName", this.showftc.buyerName);
      this.$set(this.saveData, "orderCode", this.showftc.orderCode);


      //添加了绑定的订单的id
      this.$set(this.saveData, "bindingFormInstId", this.showftc.id);

      this.loading = true;

      queryBindDtcContracts({
        formInstId: this.showftc.id
      }).then((response) => {

        this.loading = false;
        this.queryOrderData2 = response.data.datas;

        let table2Data =  [];

        for (let i = 0; i < this.queryOrderData2.length; i++) {

          if (!table2Data[i]) {
            table2Data[i] = {};
          }
          table2Data[i].table2_dtcNumber = this.queryOrderData2[i].bd_no;
          table2Data[i].table2_sellerName = this.queryOrderData2[i].bd_seller;
          table2Data[i].table2_contractAmount = this.queryOrderData2[i].bd_table1_totalAmount;
          table2Data[i].table2_id = this.queryOrderData2[i].id;
        }
        this.table2Data = table2Data;
        this.allData = _.cloneDeep(this.saveData);
      });

    },
    bindOuterCancel() {
      this.bindInnerCancel();
    },
    bindInnerConfirm() {
      this.$set(this.dialogCtrl, "outerVisible", false);
      this.$set(this.dialogCtrl, "innerVisible", false);

      if (this.buyertotcf_bindDContracts.length === 0) {
        this.bindInnerCancel();
        return;
      }

      this.hasBind = true;

      this.$set(this.saveData, "buyertotcf_bindFContracts", this.buyertotcf_bindFContracts)
      this.$set(this.saveData, "buyertotcf_bindDContracts", this.buyertotcf_bindDContracts)

      /*
       */
      /*
      //内贸多选时
      this.showdtcs = this.queryOrderData2.filter((e)=>{
         return this.saveData.buyertotcf_bindDContracts.indexOf(e.bd_no) != -1;
      });

      this.showdtcs.forEach((e,i)=>{
        e.dtcId = 5 + i +  (this.showdtcs[0].id - e.formInstId);
      });
      */


      //绑定单个内贸代码
      let  tempDts = this.queryOrderData2.find((e) => {
        return e.bd_no == this.saveData.buyertotcf_bindDContracts[0];
      });
      this.showdtcs.splice(0, 1, tempDts);

      this.table1Data = [];
      this.table2Data = [];
      this.$set(this.page, "pageSize", 30);
      this.allData = _.cloneDeep(this.saveData);
    },
    bindInnerCancel() {
      this.$set(this.dialogCtrl, "outerVisible", false);
      this.$set(this.dialogCtrl, "innerVisible", false);
      this.$set(this.page, "pageSize", 30);
      this.buyertotcf_bindDContracts = [];
      this.buyertotcf_bindFContracts = [];
      this.table1Data = [];
      this.table2Data = [];
      this.buyertotcf_selectOrder = [];
      this.canNotSelect = true;
      this.canNotSelect2 = true;
    }
  },

  beforeDestroy(){
    setStore("flow2-save-status", "unsave");
  },
  data() {
    return {
      saveData: {
          hasSaved: false,
          attachedFiles: [],
          relationFormInstId: [], //关联订单

          buyertotcf_bindFContracts: [], //绑定的订单编号
          buyertotcf_bindDContracts: [], //绑定的内贸合同,

          bindingFormInstId: '', //绑定的订单的id

          buyerName: '',
          orderCode: '',

          isSalesMan: true,
          'newApprovalName': '',

          //该流程中的所有审批项
          approvalNames: [
            "业务领导审批定金收汇通知单", "财务审批定金收汇通知单"
          ],

          newApproval: {
            "approval_opinion": "",
            "approval_username": "",
            "approval_time": "",
            "approval_div_name": ""
          },

          prevApprovals: [],

          remainApprovals: [],

          //该流程中的所有审批项
          "originApprovals": [
            {
              "approval_opinion": "",
              "approval_username": "",
              "approval_time": "",
              "approval_div_name": "业务领导审批定金收汇通知单",
              "rw" :  'R',
              item: 'item_02_01'
            }, {
              "approval_opinion": "",
              "approval_username": "",
              "approval_time": "",
              "approval_div_name": "财务审批定金收汇通知单",
              "rw" :  'R',
              item: 'item_02_02'
            }
          ]
      },
      allData: {},
      roles: {},
      sendMenus: [],
      isShowItem: false,
      isShowSpan: false,
      editable: true,
      hasBind: false,
      saveAndSend: true,
      process: ['待发事项', '待办事项', '已办事项','发起流程'],
      processNumber: 3,
      loading: false,
      page: {
        currPage: 1,
        pageSize: 30,
        totalSize: 0
      },
      dialogCtrl: {
        outerVisible: false,
        innerVisible: false,
      },
      orderNumber: '',
      foreignTradeContractNumber: '',
      buyerName: '',
      buyertotcf_selectOrder: [],
      buyertotcf_selectOrder2: [],
      buyertotcf_bindFContracts: [],
      buyertotcf_bindDContracts: [],
      canNotSelect: true,
      canNotSelect2: true,
      queryOrderData: null,
      queryOrderData2: null,
      table1Data: [],
      table2Data: [],
      showftc: null,
      showdtcs: [],
      orangeDate: '',
      pickerOrange:{
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        }
    }
  },
  props: {
  },
  components: {
    fixedForm
  }
}
</script>

<style lang="scss">
body {

    .el-dialog__wrapper {
        a {
            color: #409eff;
        }
    }
    .dialog-footer {
        text-align: center;
        button {
            margin-right: 50px;
        }
    }
}

.buyertotcf {
    padding: 20px;

    font-size: 15px;

    i.el-breadcrumb__separator {
        margin: 0 !important;
    }

    i.el-breadcrumb__separator[class*=icon] {
        margin: 0 !important;
        padding: 0 9px !important;
    }

    .buyertotcf-top {
        > h2 {
            text-align: center;
            padding: 20px;
        }
        border: 1px solid #999;

        .upload {
            padding: 20px;
            > div {
                border: 1px solid #999;
                padding: 20px 0 40px 20px;
            }

            .upload-btn {
                position: relative;
                > input {
                    opacity: 0;
                    width: 100px;
                    height: 40px;
                    position: absolute;
                    top: 0;
                    left: 0;
                }
            }
            .upload-files {

                > li {
                    width: 300px;
                    padding: 10px 0;
                    transition: all 0.5s linear;

                    &:hover {

                      >span {
                        color: #409EFF;
                      }
                    }
                  }

                font-size: 16px;
                span {
                    padding: 0 10px;
                    cursor: pointer;
                    display: inline;
                }
                span.el-icon-close:hover {
                    cursor: pointer;
                }
            }
            .upload-hint {
                font-size: 20px;
                margin-bottom: 10px;
            }
        }
    }

    a {
        color: #409EFF;
    }

    .head {
        padding: 0px 20px;
        position: relative;

        .btns {
           position: absolute;
           top: -44px;
            .bind {
                float: left;
            }
            .export {
                float: right;
            }
        }

        .select-orders {

            padding: 10px 0;

            li {
                padding: 5px 0;
            }
            .select-orders-line {
              height: 40px;
              line-height: 40px;
            }
        }

    }

    .bind-window {
        .el-form--inline .el-form-item {
            margin-right: 15px;
        }

        td {
            border: 1px solid #e6ebf5;
        }

        td:not(.el-table_1_column_1) {
            width: 120px;
            min-width: 120px;
        }

        .dialog-footer {
            text-align: center;
            button {
                margin-right: 80px;
            }
        }

        a {
            color: #409EFF;
        }

    }

    .buyertotcf-bottom {
        border: 1px solid #999;
        margin-top: 20px;
    }
}
</style>
